﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DormMS.IService;
using DormMS.Model;
using SqlSugar;
using Infrastructure.Dao;
using DormMS.Model.SearchModels;
using DormMS.Model.Enum;
using Infrastructure.Tool;
using DormMS.Model.ViewModels;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using Senparc.Weixin.MP.TenPayLib;
using Senparc.Weixin.MP.AdvancedAPIs;
using DormMS.Model.ViewModels.Activity;
using SyntacticSugar;
using DormMS.IService.Common;
using DormMS.Service.Common;
using System.Data;

namespace DormMS.Service
{
    public class OrderService : IOrderService
    {
        protected SqlSugarClient db;
        private IWxConfigService wxConfigService = new WxConfigService();
        private IMemberService memberService = new MemberService();
        private IActivityTeamMembersService activityTeamMembersService = new ActivityTeamMembersService();
        private ILogService logService = new LogService();
        private string checkUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

        public bool EditOrderDetail(OrderDetail model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<OrderDetail>(model);
            }
        }

        public bool EditOrder(Order model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<Order>(model);
            }
        }

        /// <summary>
        /// 分页获取订单列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<V_Order> GetOrderManage(OrderManageSearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                var data = db.Queryable<Order>().Where(m =>(int)m.OrderType != (int)OrderType.一分钱订单);
                if (!string.IsNullOrWhiteSpace(search.Keywords))
                {
                    data = data.Where(m => m.OrderNo.Contains(search.Keywords) || m.ReceiveName.Contains(search.Keywords)||m.ReceivePhone.Contains(search.Keywords));
                }
                if (search.Start.HasValue && search.End.HasValue)
                {
                    data = data.Where(m => m.AddTime >= search.Start.Value && m.AddTime < search.End.Value);
                }
                if (search.OrderStatus >= 0)
                {
                    data = data.Where(m => (int)m.OrderState == search.OrderStatus);
                }
                if (search.PayStatus >= 0)
                {
                    data = data.Where(m => (int)m.PayState == search.PayStatus);
                }
                if (search.SendStatus >= 0)
                {
                    data = data.Where(m => (int)m.SendStatus == search.SendStatus);
                }
                if (search.OrderType >= 0)
                {
                    data = data.Where(m => (int)m.OrderType == search.OrderType);
                }
                var list = data.OrderBy(" PayTime desc,AddTime desc").Select<Order, V_Order>("*").ToPageList(search.Skip / search.Take + 1, search.Take, ref total);
                foreach (var item in list)
                {
                    int count = db.Queryable<ReturnGoods>().Where(t => t.OrderId == item.Id&&t.Satus!=ReturnStatus.已拒绝).Count();
                    if (count > 0)
                    {
                        item.IsHaveReturn = true;
                    }
                    else
                    {
                        item.IsHaveReturn = false;
                    }
                }
                return list;
            }
        }
        /// <summary>
        /// 积分订单
        /// </summary>
        /// <param name="search"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public List<V_Order> GetPointOrderManage(OrderManageSearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                var data = db.Queryable<Order>().Where(m => (int)m.OrderType == (int)OrderType.积分订单);
                if (!string.IsNullOrEmpty(search.Keywords))
                {
                    data = data.Where(m => m.OrderNo.Contains(search.Keywords));
                }
                if (search.Start.HasValue)
                {
                    data = data.Where(m => m.AddTime >= search.Start.Value);
                }
                if (search.End.HasValue)
                {
                    DateTime end = search.End.Value.AddDays(1).Date;
                    data = data.Where(m => m.AddTime < search.End.Value);
                }
                if (search.OrderStatus >= 0)
                {
                    data = data.Where(m => (int)m.OrderState == search.OrderStatus);
                }
                if (search.SendStatus >= 0)
                {
                    data = data.Where(m => (int)m.SendStatus == search.SendStatus);
                }

                return data.OrderBy(m => m.AddTime, OrderByType.Desc).Select<Order, V_Order>("*").ToPageList(search.Skip / search.Take + 1, search.Take, ref total);
            }
        }

        /// <summary>
        /// 我的订单列表
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public List<V_Order> GetMyOrderList(int memberId)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Order>().Where(m => m.MemberId == memberId && (int)m.OrderType != (int)OrderType.积分订单 && (int)m.OrderType != (int)OrderType.一分钱订单 && (int)m.OrderState != (int)OrderStatus.已作废)
                .OrderBy(m => m.AddTime, OrderByType.Desc).Select<Order, V_Order>("*").ToList();

                foreach (V_Order item in list)
                {
                    item.OrderDetailList = db.Queryable<OrderDetail>().Where(t => t.OrderId == item.Id).ToList();

                    int count = db.Queryable<ReturnGoods>().Where(t => t.OrderId == item.Id).Count();
                    if ((item.OrderState == OrderStatus.已收货 || item.OrderState == OrderStatus.已完成) && item.SendTime.HasValue && item.SendTime.Value.AddDays(7) >= DateTime.Today && count == 0)
                    {
                        item.IsAllowReturn = true;
                    }
                    else
                    {
                        item.IsAllowReturn = false;
                    }

                }
                return list;
            }
        }

        public V_Order GetOrderModel(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelteJoin";
                var model = db.Queryable<Order>().JoinTable<Common_Area>((m, a1) => m.ReceiveProvince == a1.Id).JoinTable<Common_Area>((m, a2) => m.ReceiveCity == a2.Id).JoinTable<Common_Area>((m, a3) => m.ReceiveArea == a3.Id)
                    .Where(m => m.Id == Id).Select<Order, Common_Area, Common_Area, Common_Area, V_Order>((m, a1, a2, a3) =>
                    new V_Order
                    {
                        Id = m.Id,
                        OrderNo = m.OrderNo,
                        AddTime = m.AddTime,
                        ActivityCouponMoney = m.ActivityCouponMoney,
                        CancleReason = m.CancleReason,
                        CancleTime = m.CancleTime,
                        AactivityId = m.AactivityId,
                        CouponId = m.CouponId,
                        Discount = m.Discount,
                        ExpressId = m.ExpressId,
                        FullReduceMoney = m.FullReduceMoney,
                        InvoiceTitle = m.InvoiceTitle,
                        MemberDiscount = m.MemberDiscount,
                        MemberId = m.MemberId,
                        MemberLevel = m.MemberLevel,
                        MemberMoney = m.MemberMoney,
                        MemberName = m.MemberName,
                        OrderPoint = m.OrderPoint,
                        OrderPrice = m.OrderPrice,
                        OrderState = m.OrderState,
                        OrderType = m.OrderType,
                        PayMoney = m.PayMoney,
                        PayState = m.PayState,
                        PointsPayMoney = m.PointsPayMoney,
                        ProductPrice = m.ProductPrice,
                        PayTime = m.PayTime,
                        PayType = m.PayType,
                        PostageMoney = m.PostageMoney,
                        ReceiveAddress = m.ReceiveAddress,
                        ReceiveName = m.ReceiveName,
                        ReceiveTime = m.ReceiveTime,
                        ReceivePhone = m.ReceivePhone,
                        SendStatus = m.SendStatus,
                        Zipcode = m.Zipcode,
                        TemplateName = m.TemplateName,
                        Province = a1.Name,
                        City = a2.Name,
                        Area = a3.Name,
                        Remark = m.Remark
                    }).FirstOrDefault();
                return model;
            }
        }

        public List<OrderDetail> GetOrderDetailByOrderId(int orderId)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<OrderDetail>().Where(t => t.OrderId == orderId).ToList();
            }
        }

        public OrderDetail FindOrderDetail(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<OrderDetail>().SingleOrDefault(t => t.Id == Id);
            }
        }

        public List<V_OrderDetail> GetV_OrderDetailByOrderId(int orderId)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<OrderDetail>().Where(t => t.OrderId == orderId).Select<OrderDetail, V_OrderDetail>("*").ToList();
                var order = db.Queryable<Order>().SingleOrDefault(t => t.Id == orderId);
                foreach (var item in list)
                {
                    int count = db.Queryable<ReturnGoods>().Where(t => t.OrderDetailId == item.Id).Count();
                   
                    if (item.SendStatus != OrderDetailSendStatus.已换货 && item.SendStatus != OrderDetailSendStatus.已退货 && order.PayState == OrderPayStatus.已支付 && order.OrderState != OrderStatus.已取消 && order.OrderState != OrderStatus.已作废 && (order.OrderType == OrderType.正常订单 || order.OrderType == OrderType.抢购订单||order.OrderType==OrderType.团购订单) && count == 0)
                    {
                        if (order.ReceiveTime.HasValue && order.ReceiveTime.Value.AddDays(7) < DateTime.Today)
                        {
                            item.IsAllowReturn = false;
                        }
                        else
                        {
                            if (order.OrderType == OrderType.团购订单)
                            {
                                var act = db.Queryable<GroupMember>().SingleOrDefault(t => t.OrderNo == order.OrderNo);
                                if (act != null)
                                {
                                    var group = db.Queryable<GroupHead>().SingleOrDefault(t => t.GroupHeadID == act.GroupHeadID);
                                    if (group.CreateTime.AddHours(group.DropGroupTime) < DateTime.Now)
                                    {
                                        item.IsAllowReturn = true;
                                    }
                                    else
                                    {
                                        item.IsAllowReturn = false;
                                    }
                                }
                                else
                                {
                                    item.IsAllowReturn = false;
                                }
                            
                            }
                            else
                            {
                                item.IsAllowReturn = true;
                            }
                            
                        }
                    }
                    else
                    {
                        item.IsAllowReturn = false;
                    }

                    var returngood = db.Queryable<ReturnGoods>().Where(t => t.OrderDetailId == item.Id).FirstOrDefault();
                    if (returngood != null)
                    {
                        item.ReturnStatusDes = returngood.Satus.ToString();
                    }
                    else
                    {
                        item.ReturnStatusDes = "无";
                    }

                    if (returngood != null && (returngood.Satus == ReturnStatus.待处理 || returngood.Satus == ReturnStatus.客服处理中))
                    {
                        item.ReturnDes = "退换货中";
                    }
                    else
                    {
                        item.ReturnDes = "";
                    }
                }

                return list;
            }
        }

        public Order GetOrderInfo(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<Order>().SingleOrDefault(m => m.Id == Id);
            }
        }

        public Order GetOrderInfo(string orderNo)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<Order>().SingleOrDefault(m => m.OrderNo == orderNo);
            }
        }



        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="order"></param>
        /// <param name="productList"></param>
        public int AddOrder(Order order, List<OrderDetail> productList, OrderRecord or)
        {
            using (db = DbConfig.GetInstance())
            {
                db.IsNoLock = true;//启用无锁查询
                db.CommandTimeOut = 30000;//设置超时时间
                try
                {

                    var member = db.Queryable<Member>().FirstOrDefault(t => t.Id == order.MemberId);
                    //会员资金记录
                    MemberBalanceDetail mbd = new MemberBalanceDetail();
                    if (member != null)
                    {

                        mbd.MemberId = member.Id;
                        if (order.UsePoints > 0)
                        {
                            if (member.Points < order.UsePoints)
                            {
                                throw new Exception("积分不足");
                            }
                            //if (order.PayState == OrderPayStatus.已支付)
                            //{
                            member.Points = member.Points - order.UsePoints;

                            mbd.Point = order.UsePoints * -1;
                            mbd.MemberPoint = member.Points;
                            mbd.MemberAmount = member.Balance;
                            //}
                        }
                        if (order.MemberMoney > 0)
                        {
                            if (member.Balance < order.MemberMoney)
                            {
                                throw new Exception("余额不足");
                            }
                            //if (order.PayState == OrderPayStatus.已支付)
                            //{
                            member.Balance = member.Balance - order.MemberMoney;
                            mbd.Amount = order.MemberMoney * -1;
                            mbd.MemberAmount = member.Balance;
                            mbd.MemberPoint = member.Points;
                            //}
                        }
                    }

                    db.BeginTran();//开启事务
                    int orderId = db.Insert<Order>(order).ObjToInt();
                    if (mbd.Amount != 0 || mbd.Point != 0)
                    {
                        mbd.OrderNo = order.OrderNo;
                        mbd.OrderId = orderId;
                        mbd.Note = "订单" + order.OrderNo + "消费";

                        db.Insert<MemberBalanceDetail>(mbd);
                        if (member != null)
                        {
                            db.Update<Member>(member);
                        }
                    }

                    if (order.CouponId.HasValue)
                    {
                        var memberCoupon = db.Queryable<MemberCoupon>().FirstOrDefault(t => t.Id == order.CouponId.Value);
                        if (memberCoupon != null)
                        {
                            memberCoupon.Status = MemberCouponStatus.已使用;
                            memberCoupon.UsedTime = DateTime.Now;

                            db.Update<MemberCoupon>(memberCoupon);
                        }
                    }

                    if (order.OrderType != OrderType.一分钱订单 && productList != null && productList.Count > 0)
                    {
                        foreach (var item in productList)
                        {
                            item.OrderId = orderId;
                            item.OrderNo = order.OrderNo;
                            if (order.OrderType == OrderType.正常订单 || order.OrderType == OrderType.抢购订单 || order.OrderType == OrderType.团购订单)
                            {
                                var product = db.Queryable<Product_Spec>().FirstOrDefault(t => t.Id == item.SpecId);

                                if (product.Stock - product.WaitSendStock < item.ProductCount)
                                {
                                    throw new Exception(item.ProductName + "库存不足");
                                }
                                if (order.PayState == OrderPayStatus.未支付)
                                {
                                    product.WaitSendStock = product.WaitSendStock + item.ProductCount;
                                }
                                else
                                {
                                    product.Stock = product.Stock - item.ProductCount;
                                }
                                db.Update<Product_Spec>(product);
                                if (order.PayState == OrderPayStatus.已支付)
                                {
                                    var pro = db.Queryable<Product>().SingleOrDefault(t => t.Sku == item.ProductSku);
                                    if (pro != null)
                                    {
                                        pro.SaleCount = pro.SaleCount + item.ProductCount;
                                        db.Update(pro);
                                    }
                                }

                                if (order.OrderType == OrderType.抢购订单)
                                {
                                    var act = db.Queryable<Activity_Spike>().Where(m => m.Id == order.AactivityId.Value).FirstOrDefault();
                                    if (act == null || act.EndTime < DateTime.Now)
                                    {
                                        throw new Exception("活动已下架或已结束");
                                    }
                                    else if (act != null && act.BeginTime > DateTime.Now)
                                    {
                                        throw new Exception("活动还未开始");
                                    }

                                    var spike = db.Queryable<Activity_SpikeSpec>().Where(m => m.SpikeId == order.AactivityId.Value && m.ProductSku == item.ProductSku).FirstOrDefault();
                                    if (spike == null)
                                    {
                                        throw new Exception("抢购商品不存在");
                                    }
                                    spike.SpikeStock = spike.SpikeStock + item.ProductCount;
                                    if (spike.SpikeStock > spike.Stock)
                                    {
                                        throw new Exception("库存不足");
                                    }

                                    var oids = db.Queryable<Order>().Where(t => t.MemberId == order.MemberId && (int)t.OrderType == (int)OrderType.抢购订单 && t.AactivityId == order.AactivityId && (int)t.OrderState != (int)OrderStatus.已取消 && (int)t.OrderState != (int)OrderStatus.已作废).Select(t => t.Id).ToList().ToArray();

                                    var count = db.Queryable<OrderDetail>().Where(t => t.SpecId == item.SpecId && oids.Contains(t.OrderId)).ToList().Sum(t => t.ProductCount);
                                    if (count + item.ProductCount > spike.Limit)
                                    {
                                        throw new Exception(item.ProductName + "每人限购" + spike.Limit + "件");
                                    }

                                    db.Update<Activity_SpikeSpec>(spike);
                                }
                            }
                            else if (order.OrderType == OrderType.积分订单)
                            {
                                var product = db.Queryable<ProductExchange>().FirstOrDefault(t => t.Id == item.ProductId);
                                if (product.Stock < item.ProductCount)
                                {
                                    throw new Exception(item.ProductName + "库存不足");
                                }
                                product.Stock = product.Stock - item.ProductCount;
                                db.Update<ProductExchange>(product);
                            }

                        }
                        db.InsertRange<OrderDetail>(productList);
                    }

                    if (order.OrderType == OrderType.团购订单 && order.PayState == OrderPayStatus.已支付)
                    {
                        var act = db.Queryable<DropGroup>().SingleOrDefault(t => t.DropGroupID == order.AactivityId.Value);
                        if (order.GroupId.HasValue && order.GroupId.Value > 0)
                        {

                            GroupHead gh = db.Queryable<GroupHead>().SingleOrDefault(t => t.GroupHeadID == order.GroupId.Value);
                            gh.InvolvedNum = gh.InvolvedNum + 1;
                            bool isfanli = true;
                            decimal minPrice = db.Queryable<GroupMember>().Where(t => t.GroupHeadID == gh.GroupHeadID).Min(t => t.PayPrice).ObjToDecimal();
                            if (minPrice == act.FloorPrice)
                            {
                                isfanli = false;
                            }

                            if (gh.NowPrice - act.DropPrice >= act.FloorPrice)
                            {
                                gh.NowPrice = gh.NowPrice - act.DropPrice;
                            }
                            else
                            {
                                gh.NowPrice = act.FloorPrice;
                            }

                            db.Update<GroupHead>(gh);
                            GroupMember gm = new GroupMember();

                            gm.PayPrice = order.ProductPrice;
                            gm.UserID = order.MemberId;
                            gm.UserName = order.MemberName;
                            gm.RebatePrice = 0;
                            gm.GroupHeadID = gh.GroupHeadID;
                            gm.CreateTime = DateTime.Now;
                            gm.IsHead = false;
                            gm.IsDeleted = false;
                            gm.OrderNo = order.OrderNo;
                            gm.UserHeadImg = member.Avatar;

                            db.Insert<GroupMember>(gm);
                            //是否需要返利
                            if (isfanli)
                            {
                                List<GroupMember> gmlist = db.Queryable<GroupMember>().Where(t => t.GroupHeadID == gh.GroupHeadID && t.CreateTime < gm.CreateTime).ToList();
                                foreach (var item in gmlist)
                                {
                                    if (item.PayPrice - item.RebatePrice > gm.PayPrice)
                                    {

                                        decimal rebate = item.PayPrice - item.RebatePrice - gm.PayPrice;
                                        if (item.IsHead && gm.PayPrice == act.FloorPrice && act.IsFree)
                                        {
                                            rebate = gh.StartingPrice - item.RebatePrice;
                                        }
                                        if (rebate > 0)
                                        {
                                            item.RebatePrice = item.RebatePrice + rebate;
                                            var groupmember = db.Queryable<Member>().SingleOrDefault(t => t.Id == item.UserID);
                                            groupmember.Balance = groupmember.Balance + rebate;

                                            MemberBalanceDetail md = new MemberBalanceDetail();
                                            md.MemberId = item.UserID;
                                            md.MemberAmount = groupmember.Balance;
                                            md.Amount = rebate;
                                            md.Point = 0;
                                            md.MemberPoint = groupmember.Points;
                                            md.Note = "降拼活动返利";
                                            db.Update<GroupMember>(item);
                                            db.Update<Member>(groupmember);
                                            db.Insert<MemberBalanceDetail>(md);
                                        }
                                    }
                                }
                            }

                        }
                        else
                        {
                            GroupHead gh = new GroupHead();
                            gh.DropGroupID = order.AactivityId.Value;
                            gh.InvolvedNum = 1;
                            gh.FloorPrice = act.FloorPrice;
                            gh.StartingPrice = act.StartingPrice;
                            if (act.StartingPrice - act.DropPrice >= act.FloorPrice)
                            {
                                gh.NowPrice = act.StartingPrice - act.DropPrice;
                            }
                            else
                            {
                                gh.NowPrice = act.FloorPrice;
                            }
                            gh.DropGroupTime = act.DropGroupTime;
                            gh.CreateTime = DateTime.Now;
                            gh.DropPrice = act.DropPrice;
                            gh.IsDeleted = false;
                            gh.OrderID = order.Id;
                            gh.UserID = order.MemberId;
                            gh.UserName = order.MemberName;
                            gh.SpecificationsID = act.SpecificationsID;
                            gh.UserHeadImg = member.Avatar;

                            int groupId = db.Insert<GroupHead>(gh).ObjToInt();

                            GroupMember gm = new GroupMember();
                            gm.PayPrice = order.ProductPrice;
                            gm.UserID = order.MemberId;
                            gm.UserName = order.MemberName;
                            gm.RebatePrice = 0;
                            gm.GroupHeadID = groupId;
                            gm.CreateTime = DateTime.Now;
                            gm.IsHead = true;
                            gm.IsDeleted = false;
                            gm.OrderNo = order.OrderNo;
                            gm.UserHeadImg = member.Avatar;
                            db.Insert<GroupMember>(gm);
                        }
                    }

                    if (order.PayState == OrderPayStatus.已支付 && order.OrderPoint > 0 && member != null)
                    {

                        member.Points = member.Points + order.OrderPoint;

                        MemberBalanceDetail mbd1 = new MemberBalanceDetail();
                        mbd1.MemberId = member.Id;
                        mbd1.Amount = 0;
                        mbd1.MemberAmount = member.Balance;
                        mbd1.MemberPoint = member.Points;
                        mbd1.Point = order.OrderPoint;
                        mbd1.OrderId = order.Id;
                        mbd1.OrderNo = order.OrderNo;
                        mbd1.Note = "订单" + order.OrderNo + "支付成功获得";

                        db.Insert<MemberBalanceDetail>(mbd1);
                        db.Update(member);
                    }

                    //订单操作记录
                    or.OrderId = orderId;
                    or.OrderNo = order.OrderNo;
                    or.OrderStatus = order.OrderState;
                    or.PayStatus = order.PayState;
                    or.SendStatus = order.SendStatus;
                    or.OperationNote = "提交订单";
                    or.Ip = Generator.GetIP();

                    db.Insert<OrderRecord>(or);

                    db.CommitTran();//提交事务
                    return orderId;
                }
                catch (Exception)
                {
                    db.RollbackTran();//回滚事务
                    throw;
                }
            }
        }

        public bool UpdateOrder(Order order)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<Order>(order);
            }
        }

        /// <summary>
        /// 订单确认支付
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="operationUserType">操作用户类型0会员 1后台用户</param>
        /// <param name="userId">操作用户Id</param>
        public void PayOrder(string orderNo, OrderRecord or)
        {
            var config = wxConfigService.GetConfig();
            var token = wxConfigService.GetCurrentToken(checkUrl, config.AppId, config.AppSecret);
            using (db = DbConfig.GetInstance())
            {
                try
                {
                    
                    var order = db.Queryable<Order>().Where(t => t.OrderNo == orderNo).FirstOrDefault();
                    if (order == null)
                    {
                        throw new Exception("订单不存在");
                    }
                    if (order.PayState != OrderPayStatus.未支付)
                    {
                        throw new Exception("该订单已支付");
                    }
                    var member = db.Queryable<Member>().SingleOrDefault(t => t.Id == order.MemberId);
                    db.IsNoLock = true;//启用无锁查询
                    db.CommandTimeOut = 30000;//设置超时时间
                    db.BeginTran();//开启事务
                    if (member != null)
                    {
                        if (order.OrderPoint > 0)
                        {
                            member.Points = member.Points + order.OrderPoint;



                            MemberBalanceDetail mbd = new MemberBalanceDetail();
                            mbd.MemberId = member.Id;
                            mbd.Amount = 0;
                            mbd.MemberAmount = member.Balance;
                            mbd.MemberPoint = member.Points;
                            mbd.Point = order.OrderPoint;
                            mbd.OrderId = order.Id;
                            mbd.OrderNo = order.OrderNo;
                            mbd.Note = "订单" + order.OrderNo + "支付成功";

                            db.Insert<MemberBalanceDetail>(mbd);
                        }
                        member.TotalPay = member.TotalPay + order.PayMoney;
                        var level = db.Queryable<MemberLevel>().Where(t => t.Id > member.MemberLevel).OrderBy(t => t.Id).FirstOrDefault();
                        if (level != null && level.Amount <= member.TotalPay)
                        {
                            member.MemberLevel = level.Id;
                        }
                        db.Update<Member>(member);
                    }
                    order.PayTime = DateTime.Now;
                    order.PayState = OrderPayStatus.已支付;
                    db.Update<Order>(order);
                    //更新库存
                    List<OrderDetail> odlist = db.Queryable<OrderDetail>().Where(t => t.OrderId == order.Id).ToList();
                    foreach (var item in odlist)
                    {
                        var product = db.Queryable<Product_Spec>().SingleOrDefault(t => t.Id == item.SpecId);
                        if (product != null)
                        {
                            product.Stock = product.Stock - 1;
                            product.WaitSendStock = product.WaitSendStock - 1;

                            db.Update<Product_Spec>(product);
                        }
                        var pro = db.Queryable<Product>().SingleOrDefault(t => t.Sku == item.ProductSku);
                        if (pro != null)
                        {
                            pro.SaleCount = pro.SaleCount + item.ProductCount;
                            db.Update(pro);
                        }
                    }

                    if (order.OrderType == OrderType.团购订单)
                    {
                        var act = db.Queryable<DropGroup>().SingleOrDefault(t => t.DropGroupID == order.AactivityId.Value);
                        if (order.GroupId.HasValue && order.GroupId.Value > 0)
                        {

                            GroupHead gh = db.Queryable<GroupHead>().SingleOrDefault(t => t.GroupHeadID == order.GroupId.Value);
                            gh.InvolvedNum = gh.InvolvedNum + 1;
                            bool isfanli = true;

                            decimal minPrice = db.Queryable<GroupMember>().Where(t => t.GroupHeadID == gh.GroupHeadID).Min(t => t.PayPrice).ObjToDecimal();
                            if (minPrice == act.FloorPrice)
                            {
                                isfanli = false;
                            }

                            if (gh.NowPrice - act.DropPrice >= act.FloorPrice)
                            {
                                gh.NowPrice = gh.NowPrice - act.DropPrice;
                            }
                            else
                            {
                                gh.NowPrice = act.FloorPrice;
                            }

                            db.Update<GroupHead>(gh);

                            if (gh.NowPrice == act.FloorPrice)
                            {

                            }
                            GroupMember gm = new GroupMember();

                            gm.PayPrice = order.ProductPrice;
                            gm.UserID = order.MemberId;
                            gm.UserName = order.MemberName;
                            gm.RebatePrice = 0;
                            gm.GroupHeadID = gh.GroupHeadID;
                            gm.CreateTime = DateTime.Now;
                            gm.IsHead = false;
                            gm.IsDeleted = false;
                            gm.OrderNo = order.OrderNo;
                            gm.UserHeadImg = member.Avatar;
                            if (db.Insert<GroupMember>(gm).ObjToInt() > 0)
                            {
                                #region 参与降价拼团推送
                                CustomApi.SendTextAsync(token, member.OpenId, $"您已成功参与了降价拼团活动。支付了{gm.PayPrice}元。");
                                #endregion
                            }
                            //是否需要返利
                            if (isfanli)
                            {
                                List<GroupMember> gmlist = db.Queryable<GroupMember>().Where(t => t.GroupHeadID == gh.GroupHeadID && t.CreateTime < gm.CreateTime).ToList();
                                foreach (var item in gmlist)
                                {
                                    if (item.PayPrice - item.RebatePrice > gm.PayPrice)
                                    {

                                        decimal rebate = item.PayPrice - item.RebatePrice - gm.PayPrice;
                                        //团长是否免单
                                        if (item.IsHead && gm.PayPrice == act.FloorPrice && act.IsFree)
                                        {
                                            rebate = gh.StartingPrice - item.RebatePrice;
                                        }
                                        if (rebate > 0)
                                        {
                                            item.RebatePrice = item.RebatePrice + rebate;
                                            var groupmember = db.Queryable<Member>().SingleOrDefault(t => t.Id == item.UserID);
                                            groupmember.Balance = groupmember.Balance + rebate;

                                            MemberBalanceDetail md = new MemberBalanceDetail();
                                            md.MemberId = item.UserID;
                                            md.MemberAmount = groupmember.Balance;
                                            md.Amount = rebate;
                                            md.Point = 0;
                                            md.MemberPoint = groupmember.Points;
                                            md.Note = "降拼活动返利";
                                            db.Update<GroupMember>(item);
                                            db.Update<Member>(groupmember);
                                            int mdid= db.Insert<MemberBalanceDetail>(md).ObjToInt();

                                            #region 返利推送消息
                                            if (mdid > 0)
                                            {
                                                CustomApi.SendTextAsync(token, groupmember.OpenId, $"您通过降价拼团活动获得返利{rebate}元。");
                                            }
                                            #endregion
                                        }
                                    }
                                }
                            }

                        }
                        else
                        {
                            GroupHead gh = new GroupHead();
                            gh.DropGroupID = order.AactivityId.Value;
                            gh.InvolvedNum = 1;
                            gh.FloorPrice = act.FloorPrice;
                            gh.StartingPrice = act.StartingPrice;
                            if (act.StartingPrice - act.DropPrice >= act.FloorPrice)
                            {
                                gh.NowPrice = act.StartingPrice - act.DropPrice;
                            }
                            else
                            {
                                gh.NowPrice = act.FloorPrice;
                            }
                            gh.DropGroupTime = act.DropGroupTime;
                            gh.CreateTime = DateTime.Now;
                            gh.DropPrice = act.DropPrice;
                            gh.IsDeleted = false;
                            gh.OrderID = order.Id;
                            gh.UserID = order.MemberId;
                            gh.UserName = order.MemberName;
                            gh.SpecificationsID = act.SpecificationsID;
                            gh.UserHeadImg = member.Avatar;
                            int groupId = db.Insert<GroupHead>(gh).ObjToInt();

                            GroupMember gm = new GroupMember();
                            gm.PayPrice = order.ProductPrice;
                            gm.UserID = order.MemberId;
                            gm.UserName = order.MemberName;
                            gm.RebatePrice = 0;
                            gm.GroupHeadID = groupId;
                            gm.CreateTime = DateTime.Now;
                            gm.IsHead = true;
                            gm.IsDeleted = false;
                            gm.OrderNo = order.OrderNo;
                            gm.UserHeadImg = member.Avatar;
                            int gmid = db.Insert<GroupMember>(gm).ObjToInt();

                            #region 降拼活动开团推送
                            if (gmid > 0)
                            {
                                CustomApi.SendTextAsync(token, member.OpenId, $"您已成功发起了降价拼团活动。支付了{gm.PayPrice}元。");
                            }
                            #endregion
                        }
                    }
                    else if (order.OrderType == OrderType.一分钱订单)
                    {
                        var act = db.Queryable<Activity>().FirstOrDefault(t => t.Id == order.AactivityId.Value);
                        //加入团
                        if (order.GroupId.HasValue && order.GroupId.Value > 0)
                        {
                            var at = db.Queryable<Model.ActivityTeam>().SingleOrDefault(t => t.Id == order.GroupId.Value);
                            ActivityTeamMembers atm = new ActivityTeamMembers();
                            atm.ActivityId = order.AactivityId.Value;
                            atm.ActivityTeamId = order.GroupId.Value;
                            atm.IsHead = false;
                            atm.JoinTime = DateTime.Now;
                            atm.OrderNo = order.OrderNo;
                            atm.PaymentAmount = order.PayMoney;
                            atm.RefundStatus = 2;
                            atm.UserHeadImg = member.Avatar;
                            atm.UserId = member.Id;
                            atm.UserName = member.NickName;
                            atm.WinningStatus = 4;
                            int atmid= db.Insert<ActivityTeamMembers>(atm).ObjToInt();
                            
                            if (atmid > 0)
                            {
                                at.NowParticipateNum = at.NowParticipateNum + 1;
                                if (at.NowParticipateNum == at.ParticipateNum)
                                {
                                    at.TeamStatus = 2;
                                    #region 推送组团成功消息
                                    var uids = db.Queryable<ActivityTeamMembers>().Where(t => t.ActivityTeamId == atm.ActivityTeamId).ToList().Select(t => t.UserId).ToArray();
                                    var memberList = db.Queryable<Member>().Where(t => uids.Contains(t.Id)).ToList();
                                    foreach (var item in memberList)
                                    {
                                        CustomApi.SendTextAsync(token, item.OpenId, $"您参加的'{act.ActivityName}'活动已经组团成功，请赶快去抽奖吧！");
                                    }
                                    #endregion

                                }
                                db.Update<Model.ActivityTeam>(at);

                                #region 微信推送入团消息
                                CustomApi.SendTextAsync(token, member.OpenId, $"您已成功参加'{act.ActivityName}'活动，花费{order.PayMoney}元。");
                                #endregion
                            }

                        }
                        //开新团
                        else
                        {
                            Model.ActivityTeam at = new Model.ActivityTeam();
                            at.ActivityId = order.AactivityId.Value;
                            at.ActivityName = act.ActivityName;
                            at.ActivityPrice = act.ActivityPrice;
                            at.ContinuedTime = act.ContinuedTime;
                            at.EndTime = DateTime.Now.AddHours(act.ContinuedTime);
                            at.CreateTime = DateTime.Now;
                            at.NowParticipateNum = 1;
                            at.ParticipateNum = act.PeopleNum;
                            at.TeamStatus = 1;
                            at.UserId = order.MemberId;
                            at.UserHeadImg = member.Avatar;
                            at.UserName = member.NickName;
                            if (at.NowParticipateNum == at.ParticipateNum)
                            {
                                at.TeamStatus = 2;
                                #region 推送组团成功消息

                                CustomApi.SendTextAsync(token, member.OpenId, $"您参加的'{act.ActivityName}'活动已经组团成功，快去抽奖吧！");
                                #endregion
                            }
                            int atid = db.Insert<Model.ActivityTeam>(at).ObjToInt();
                            ActivityTeamMembers atm = new ActivityTeamMembers();
                            atm.ActivityId = order.AactivityId.Value;
                            atm.ActivityTeamId = atid;
                            atm.IsHead = true;
                            atm.JoinTime = DateTime.Now;
                            atm.OrderNo = order.OrderNo;
                            atm.PaymentAmount = order.PayMoney;
                            atm.RefundStatus = 2;
                            atm.UserHeadImg = member.Avatar;
                            atm.UserId = member.Id;
                            atm.UserName = member.NickName;
                            atm.WinningStatus = 4;
                            int amid = db.Insert<ActivityTeamMembers>(atm).ObjToInt();
                            #region 推送开团成功消息
                            string winstr = "";
                            if (act.IsWinning)
                            {
                                winstr = "（您是团长，抽奖必中）";
                            }
                            if (amid > 0)
                            {
                                CustomApi.SendTextAsync(token, member.OpenId, $"您参加了'{act.ActivityName}'活动，花费{order.PayMoney}元。{winstr}");
                            }
                            #endregion
                        }
                    }


                    //订单操作记录
                    or.OrderId = order.Id;
                    or.OrderNo = order.OrderNo;
                    or.OrderStatus = order.OrderState;
                    or.PayStatus = order.PayState;
                    or.SendStatus = order.SendStatus;
                    or.OperationNote = "订单支付";
                    or.Ip = Generator.GetIP();

                    db.Insert<OrderRecord>(or);

                    db.CommitTran();//提交事务
                }
                catch (Exception ex)
                {
                    db.RollbackTran();//回滚事务

                    throw ex;
                }
            }
        }

        /// <summary>
        /// 一分钱活动抽奖
        /// </summary>
        /// <param name="actId"></param>
        /// <param name="prize"></param>
        /// <param name="member"></param>
        /// <param name="teammember"></param>
        /// <returns></returns>
        public bool YiFenDraw(int actId, Member member, V_ActivityTeamMembers teammember, ref DrawReward prize)
        {
            bool success = false;
            using (db = DbConfig.GetInstance())
            {
                try
                {
                    db.BeginTran();//开启事务

                    //没中奖并且设置了团长必中，重新抽必中的奖
                    if (prize == null)
                    {
                        //判断是否团长
                        if (teammember.IsHead)
                        {
                            //是团长的话判断是否必中
                            if (teammember.IsWinning)
                            {
                                prize = db.Queryable<DrawReward>().OrderBy(p => p.WinRate, OrderByType.Desc).FirstOrDefault(p => p.DrawId == actId && p.Count - p.WinningCount > 0);
                                if (prize != null)
                                {
                                    if (prize.RewardType == RewardType.实体商品)
                                    {
                                        var secpid = prize.ProductSecpId;
                                        var pro = db.Queryable<Product_Spec>().SingleOrDefault(t => t.Id == secpid);
                                        if (pro == null)
                                        {
                                            prize = null;
                                        }
                                    }
                                    else if (prize.RewardType == RewardType.优惠券)
                                    {
                                        var secpid = prize.ProductSecpId;
                                        var coupon = db.Queryable<Coupon>().SingleOrDefault(t => t.Id == secpid);
                                        if (coupon == null)
                                        {
                                            prize = null;
                                        }
                                    }
                                    else
                                    {
                                        prize.WinningCount = prize.WinningCount + 1;
                                        db.Update(prize);
                                    }
                                    if (prize.Count - prize.WinningCount < 0)
                                    {
                                        prize = null;
                                    }
                                }
                            }
                        }
                    }
                    //如果还是没中谢谢惠顾
                    if (prize == null)
                    {
                        //没中
                        var model = db.Queryable<Model.ActivityTeamMembers>().FirstOrDefault(p => p.Id == teammember.Id);
                        model.DrawId = 0;
                        model.DrawRewardName = "谢谢惠顾";
                        model.WinningStatus = 2;
                        model.RefundStatus = 2;
                        db.Update<Model.ActivityTeamMembers>(model);
                    }
                    else
                    {

                        //中奖
                        var model = db.Queryable<Model.ActivityTeamMembers>().FirstOrDefault(p => p.Id == teammember.Id);
                        model.DrawId = prize.Id;
                        model.DrawRewardName = prize.RewardName;
                        model.WinningStatus = 1;
                        db.Update<Model.ActivityTeamMembers>(model);

                        if (prize.RewardType == RewardType.奖励积分)
                        {
                            var detail = new MemberBalanceDetail()
                            {
                                AddTime = DateTime.Now,
                                IsDeleted = false,
                                MemberId = member.Id,
                                Point = prize.Points,
                                MemberAmount = member.Balance,
                                MemberPoint = member.Points,
                                Note = "积分抽奖奖品",
                                AddUserId = 0,
                            };
                            if (detail.Point != 0)
                            {
                                member.Points = member.Points + detail.Point;


                                detail.MemberPoint = member.Points;
                            }
                            if (detail.Amount != 0)
                            {
                                member.Balance = member.Balance + detail.Amount;
                                detail.MemberAmount = member.Balance;
                                member.TotalPay = member.TotalPay + detail.Amount;
                            }
                            db.Insert<MemberBalanceDetail>(detail);
                            db.Update<Member>(member);
                        }
                        //如果是优惠券，则更新用户优惠券表
                        if (prize.RewardType == RewardType.优惠券)
                        {
                            var memberCoupon = new MemberCoupon()
                            {
                                AddTime = DateTime.Now,
                                IsDeleted = false,
                                SourceType = MemberCouponSource.积分抽奖,
                                CouponId = prize.ProductSecpId,
                                MemberId = member.Id,
                                Status = MemberCouponStatus.未使用,
                            };
                            db.Insert(memberCoupon);
                        }
                        if (prize.RewardType == RewardType.实体商品)
                        {
                            var ProductSecpId = prize.ProductSecpId;
                            var productspec = db.Queryable<Model.Product_Spec>().SingleOrDefault(t => t.Id == ProductSecpId);
                            var product = db.Queryable<Model.Product>().SingleOrDefault(t => t.Sku == productspec.ProductSku);
                            var order = db.Queryable<Model.Order>().SingleOrDefault(t => t.OrderNo == teammember.OrderNo);
                            order.OrderState = OrderStatus.已确认;
                            db.Update<Model.Order>(order);
                            var orderdetail = new OrderDetail()
                            {
                                AddTime = DateTime.Now,
                                CostPrice = product.Price,
                                DiscountPrice = teammember.PaymentAmount,
                                ImgUrl = product.ImgUrl,
                                IsDeleted = false,
                                MarketPrice = product.MarketPrice,
                                OrderId = order.Id,
                                OrderNo = teammember.OrderNo,
                                Points = 0,
                                ProductCount = 1,
                                ProductDesc = product.Description,
                                ProductId = product.Id,
                                ProductName = product.Name,
                                ProductPrice = product.Price,
                                ProductSku = product.Sku,
                                SendStatus = 0,
                                SpecId = productspec.Id,
                                SpecKey = productspec.SpecIds,
                                SpecName = productspec.SpecNames
                            };
                            db.Insert<Model.OrderDetail>(orderdetail);
                           
                        }
                    }
                    db.CommitTran();//提交事务
                    if (prize != null && prize.RewardType == RewardType.实体商品)
                    {
                        var config = wxConfigService.GetConfig();
                        var token = wxConfigService.GetCurrentToken(checkUrl, config.AppId, config.AppSecret);
                        CustomApi.SendTextAsync(token, member.OpenId, $"恭喜您获得幸运大奖，稍后我们会为您派发奖品，请您耐心等待。");
                    }

                    success = true;
                    return success;
                }
                catch (Exception e)
                {
                    db.RollbackTran();//回滚事务
                    success = false;
                    return success;
                }
            }
        }

        public void AddOrderRecord(OrderRecord model)
        {
            using (db = DbConfig.GetInstance())
            {
                db.Insert<OrderRecord>(model);
            }
        }

        public void DelOrder(int Id, OrderRecord or)
        {
            using (db = DbConfig.GetInstance())
            {
                var order = db.Queryable<Order>().FirstOrDefault(t => t.Id == Id);
                if (order != null)
                {
                    if (order.OrderState == OrderStatus.已取消 || order.OrderState == OrderStatus.已作废)
                    {
                        order.IsDeleted = true;
                        db.Update<Order>(order);

                        or.OrderId = Id;
                        or.OrderNo = order.OrderNo;
                        or.OrderStatus = order.OrderState;
                        or.PayStatus = order.PayState;
                        or.SendStatus = order.SendStatus;
                        or.OperationNote = "删除订单";
                        or.Ip = Generator.GetIP();

                        db.Insert<OrderRecord>(or);
                    }
                    else
                    {
                        throw new Exception("只能删除取消的订单");
                    }

                }
                else
                {
                    throw new Exception("订单不存在");
                }
            }
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderId">订单Id</param>
        public void CancelOrder(int orderId, OrderRecord or)
        {
            using (db = DbConfig.GetInstance())
            {
                try
                {

                    db.IsNoLock = true;//启用无锁查询
                    db.CommandTimeOut = 30000;//设置超时时间
                    var order = db.Queryable<Order>().FirstOrDefault(t => t.Id == orderId);
                    if (order.OrderState == OrderStatus.已取消 || order.OrderState == OrderStatus.已作废)
                    {
                        throw new Exception("该订单" + order.OrderState.ToString());
                    }

                    if (order.PayState == OrderPayStatus.未支付)
                    {
                        var member = db.Queryable<Member>().SingleOrDefault(t => t.Id == order.MemberId);
                        db.BeginTran();//开启事务
                        if (member != null && (order.UsePoints > 0 || order.MemberMoney > 0))
                        {
                            MemberBalanceDetail mbd = new MemberBalanceDetail();

                            if (order.UsePoints > 0)
                            {
                                member.Points = member.Points + order.UsePoints;
                            }

                            if (order.MemberMoney > 0)
                            {
                                member.Balance = member.Balance + order.MemberMoney;
                            }

                            mbd.MemberAmount = member.Balance;
                            mbd.MemberPoint = member.Points;
                            mbd.Amount = order.MemberMoney;
                            mbd.Point = order.UsePoints;
                            mbd.MemberId = member.Id;
                            mbd.OrderId = order.Id;
                            mbd.OrderNo = order.OrderNo;
                            mbd.Note = "取消订单退回";

                            db.Insert<MemberBalanceDetail>(mbd);
                            db.Update<Member>(member);
                        }

                        order.OrderState = OrderStatus.已取消;
                        db.Update<Order>(order);
                        if (order.OrderType == OrderType.正常订单 || order.OrderType == OrderType.抢购订单)
                        {
                            //更新库存
                            List<OrderDetail> odlist = db.Queryable<OrderDetail>().Where(t => t.OrderId == order.Id).ToList();
                            foreach (var item in odlist)
                            {
                                var product = db.Queryable<Product_Spec>().SingleOrDefault(t => t.Id == item.SpecId);
                                if (product != null)
                                {
                                    product.WaitSendStock = product.WaitSendStock - 1;

                                    db.Update<Product_Spec>(product);
                                }

                                if (order.OrderType == OrderType.抢购订单)
                                {
                                    var spike = db.Queryable<Activity_SpikeSpec>().Where(m => m.SpikeId == order.AactivityId.Value && m.ProductSku == item.ProductSku).FirstOrDefault();
                                    spike.SpikeStock = spike.SpikeStock - 1;
                                    db.Update<Activity_SpikeSpec>(spike);
                                }
                            }
                        }

                        //订单操作记录
                        or.OrderId = order.Id;
                        or.OrderNo = order.OrderNo;
                        or.OrderStatus = order.OrderState;
                        or.PayStatus = order.PayState;
                        or.SendStatus = order.SendStatus;
                        or.OperationNote = "订单取消";
                        or.Ip = Generator.GetIP();

                        db.Insert<OrderRecord>(or);

                        db.CommitTran();//提交事务
                    }
                    else
                    {
                        throw new Exception("已经支付的订单无法取消");
                    }
                }
                catch (Exception)
                {
                    db.RollbackTran();//回滚事务
                    throw;
                }
            }

        }

        /// <summary>
        /// 确认订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="or"></param>
        public void ConfirmOrder(int orderId, OrderRecord or)
        {
            using (db = DbConfig.GetInstance())
            {
                var order = db.Queryable<Order>().FirstOrDefault(t => t.Id == orderId);
                if (order.OrderState == OrderStatus.待确认 && order.PayState == OrderPayStatus.已支付)
                {
                    order.OrderState = OrderStatus.已确认;
                    db.Update<Order>(order);

                    //订单操作记录
                    or.OrderId = order.Id;
                    or.OrderNo = order.OrderNo;
                    or.OrderStatus = order.OrderState;
                    or.PayStatus = order.PayState;
                    or.SendStatus = order.SendStatus;
                    or.OperationNote = "订单确认";
                    or.Ip = Generator.GetIP();

                    db.Insert<OrderRecord>(or);
                }
                else
                {
                    throw new Exception("该订单无法确认");
                }
            }
        }

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <param name="key">W:正常订单，T:团购订单，P:积分订单，X:限时抢购订单，Y:一分钱活动订单,D:退款单号</param>
        /// <returns></returns>
        public string GetSerialNumber(string key)
        {
            using (var _db = DbConfig.GetInstance())
            {
                _db.CurrentFilterKey = "";
                _db.IsNoLock = false;
                var os = _db.Queryable<OrderSerial>().FirstOrDefault(t => t.Type == key);
                if (os.Time.Date == DateTime.Today)
                {
                    os.Number = os.Number + 1;
                }
                else
                {
                    os.Number = 1;
                    os.Time = DateTime.Today;
                }
                _db.Update<OrderSerial>(os);
                _db.IsNoLock = true;
                string dateNumber = DateTime.Today.ToString("yyMMdd");
                return key + dateNumber + os.Number.ToString("00000");
            }
        }
        /// <summary>
        /// 订单操作记录
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<V_OrderRecord> GetOrderRecord(int orderId)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<OrderRecord>().Where(t => t.OrderId == orderId).Select<OrderRecord, V_OrderRecord>("*").OrderBy(t => t.AddTime, OrderByType.Desc).ToList();
                foreach (var item in list)
                {
                    if (item.OperationUserType == 1)
                    {
                        var user = db.Queryable<UserInfo>().SingleOrDefault(t => t.Id == item.OperationId);
                        if (user != null)
                        {
                            item.OpUserName = user.UserName;
                        }
                    }
                    else
                    {
                        var user = db.Queryable<Member>().SingleOrDefault(t => t.Id == item.OperationId);
                        if (user != null)
                        {
                            item.OpUserName = user.NickName;
                        }
                    }
                }
                return list;
            }
        }


        public List<V_Order> GetSendOrderList(OrderManageSearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                var data = db.Queryable<Order>().Where(m => (int)m.OrderState == (int)OrderStatus.已确认 && (int)m.PayState == (int)OrderPayStatus.已支付);
                if (!string.IsNullOrEmpty(search.Keywords))
                {
                    data = data.Where(m => m.OrderNo.Contains(search.Keywords) || m.ReceiveName.Contains(search.Keywords));
                }
                //if (search.Start.HasValue)
                //{
                //    data = data.Where(m => m.AddTime >= search.Start.Value);
                //}
                //if (search.End.HasValue)
                //{
                //    DateTime end = search.End.Value.AddDays(1).Date;
                //    data = data.Where(m => m.AddTime < search.End.Value);
                //}
                if (search.SendStatus >= 0)
                {
                    data = data.Where(m => (int)m.SendStatus == search.SendStatus);
                }
                if (search.Start != null && search.End != null)
                {
                    data = data.Where(m => m.AddTime > search.Start && m.AddTime < search.End);
                }
                if (search.OrderType >= 0)
                {
                    data = data.Where(m => (int)m.OrderType == search.OrderType);
                }

               

                var list = data.OrderBy(m => m.AddTime, OrderByType.Desc).Select<Order, V_Order>("*").ToPageList(search.Skip / search.Take + 1, search.Take, ref total);
                

                return list;
            }
        }

        public List<V_Delivery> GetDeliveryListByOrderId(int orderId)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelteJoin";
                var list = db.Queryable<Delivery>().JoinTable<UserInfo>((m, u) => m.AddUserId == u.Id).Where(m => m.OrderId == orderId).OrderBy(m => m.AddTime, OrderByType.Desc)
                    .Select<Delivery, UserInfo, V_Delivery>((m, u) => new V_Delivery { Id = m.Id, OrderId = m.OrderId, OrderNo = m.OrderNo, InvoiceNo = m.InvoiceNo, AddUserName = u.UserName, Address = m.Address, Note = m.Note, AddTime = m.AddTime, Consignee = m.Consignee, ShippingName = m.ShippingName }).ToList();
                return list;
            }
        }

        public void AddDelivery(Delivery model, int[] ids)
        {
            using (db = DbConfig.GetInstance())
            {
                var detaillist = db.Queryable<OrderDetail>().Where(t => (int)t.SendStatus == (int)OrderDetailSendStatus.未发货 && ids.Contains(t.Id)).ToList();
                if (detaillist != null && detaillist.Count > 0)
                {
                    try
                    {
                        db.IsNoLock = true;//启用无锁查询
                        db.CommandTimeOut = 30000;//设置超时时间
                        db.BeginTran();//开启事务
                        var order = db.Queryable<Order>().SingleOrDefault(t => t.Id == detaillist[0].OrderId);
                        int Id = db.Insert<Delivery>(model).ObjToInt();

                        foreach (var item in detaillist)
                        {
                            item.SendStatus = OrderDetailSendStatus.已发货;
                            item.DeliveryId = Id;
                            db.Update<OrderDetail>(item);
                        }

                        int pcount = db.Queryable<OrderDetail>().Where(t => t.OrderId == order.Id).Count();
                        int scount = db.Queryable<OrderDetail>().Where(t => t.OrderId == order.Id && (int)t.SendStatus == (int)OrderDetailSendStatus.已发货).Count();
                        if (scount >= pcount)
                        {
                            order.SendStatus = OrderSendStatus.已发货;
                        }
                        else
                        {
                            order.SendStatus = OrderSendStatus.部分发货;
                        }
                        order.SendTime = DateTime.Now;
                        db.Update<Order>(order);

                        db.CommitTran();
                    }
                    catch (Exception)
                    {
                        db.RollbackTran();//回滚事务
                        throw;
                    }
                }
                else
                {
                    throw new Exception("商品都已发货");
                }
            }
        }

        public int GetMemberSpikeCount(int memberId, int productId)
        {
            using (db = DbConfig.GetInstance())
            {
                var orderids = db.Queryable<Order>().Where(t => t.MemberId == memberId && (int)t.OrderType == (int)OrderType.抢购订单 && ((int)t.OrderState != (int)OrderStatus.已作废 || (int)t.OrderState != (int)OrderStatus.已取消)).ToList().Select(t => t.Id).ToArray();
                if (orderids != null && orderids.Length > 0)
                {
                    return db.Queryable<OrderDetail>().Where(t => orderids.Contains(t.OrderId) && t.ProductId == productId).ToList().Sum(t => t.ProductCount);
                }
                return 0;
            }
        }
        /// <summary>
        /// 获取我参与的降拼活动订单
        /// </summary>
        /// <param name="skip"></param>
        /// <param name="take"></param>
        /// <param name="memberId"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public IEnumerable<V_Order> GetGroupOrderList(int skip, int take, int memberId, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Model.Order>()
                    .OrderBy(o => o.AddTime, OrderByType.Desc).Where(m => m.OrderType == OrderType.团购订单 && m.PayState == OrderPayStatus.已支付 && m.MemberId == memberId)
                    .ToPageList(skip / take + 1, take, ref total)
                    .Select(s => new V_Order()
                    {
                        PayMoney = s.PayMoney,
                        Id = s.Id,
                        OrderDetailList = db.Queryable<Model.OrderDetail>().Where(t => t.OrderId == s.Id).ToList(),
                        SendStatus = s.SendStatus,
                        OrderState = s.OrderState,
                        ProductPrice = s.ProductPrice
                    }).ToList();
                return list;
            }
        }

        #region 积分订单
        public List<V_Order> GetMyPointOrderList(int memberId)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Order>().Where(t => (int)t.OrderType == (int)OrderType.积分订单 && t.MemberId == memberId && (int)t.PayState == (int)OrderPayStatus.已支付)
                    .OrderBy(t => t.AddTime, OrderByType.Desc).Select<Order, V_Order>("*").ToList();

                foreach (var item in list)
                {
                    item.OrderDetailList = db.Queryable<OrderDetail>().Where(t => t.OrderId == item.Id).ToList();
                }
                return list;
            }
        }

        #endregion

        #region 退货单

        public int AddReturnGoods(ReturnGoods model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Insert<ReturnGoods>(model).ObjToInt();
            }
        }

        public List<V_ReturnGoods> GetReturnGoodsManage(ReturnGoodsSearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                var data = db.Queryable<ReturnGoods>();
                if (!string.IsNullOrEmpty(search.Keywords))
                {
                    data = data.Where(m => m.OrderNo.Contains(search.Keywords));
                }
                if (search.ReturnStatus >= 0)
                {
                    data = data.Where(m => (int)m.Satus == search.ReturnStatus);
                }
                if (search.ReturnType >= 0)
                {
                    data = data.Where(m => m.ReturnType == search.ReturnType);
                }
                if (search.BeginTime.HasValue && search.EndTime.HasValue)
                {
                    data = data.Where(m => m.AddTime > search.BeginTime && m.AddTime < search.EndTime);
                }
                var list = data.OrderBy(m => m.AddTime, OrderByType.Desc).Select<ReturnGoods, V_ReturnGoods>("*").ToPageList(search.Skip / search.Take + 1, search.Take, ref total);

                foreach (var item in list)
                {
                    item.orderDetail = db.Queryable<OrderDetail>().SingleOrDefault(t => t.Id == item.OrderDetailId);
                }

                return list;
            }
        }

        public List<V_ReturnGoods> GetMyReturnGoodsList(int memberId)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<ReturnGoods>().Where(t => t.MemberId == memberId).OrderBy(t => t.AddTime, OrderByType.Desc).Select<ReturnGoods, V_ReturnGoods>("*").ToList();
                foreach (var item in list)
                {
                    item.orderDetail = db.Queryable<OrderDetail>().SingleOrDefault(t => t.Id == item.OrderDetailId);
                }

                return list;
            }
        }

        public V_ReturnGoods FindReturnGoods(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                var model = db.Queryable<ReturnGoods>().Select<ReturnGoods, V_ReturnGoods>("*").SingleOrDefault(t => t.Id == Id);
                var order = db.Queryable<Order>().SingleOrDefault(t => t.Id == model.OrderId);
                //model.OrderDetailList = db.Queryable<OrderDetail>().Where(t => t.OrderId == model.OrderId).ToList();
                model.orderDetail = db.Queryable<OrderDetail>().SingleOrDefault(t => t.Id == model.OrderDetailId);
                model.OrderPrice = order.OrderPrice;
                model.PostageMoney = order.PostageMoney;
                model.ProductPrice = model.orderDetail.DiscountPrice * model.orderDetail.ProductCount;

                if (order.OrderType == OrderType.团购订单)
                {
                    var act = db.Queryable<GroupMember>().SingleOrDefault(t => t.OrderNo == order.OrderNo);
                    model.RebatePrice = act.RebatePrice;
                }
                else
                {
                    model.RebatePrice = 0;
                }

                return model;
            }
        }

        public ReturnGoods GetReturnGoodsInfo(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<ReturnGoods>().SingleOrDefault(t => t.Id == Id);
            }
        }

        public bool EditReturnGoods(ReturnGoods model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<ReturnGoods>(model);
            }
        }

        /// <summary>
        /// 确认退款逻辑
        /// </summary>
        /// <param name="model"></param>
        /// <param name="rmoney"></param>
        /// <param name="pmoney"></param>
        /// <param name="mmoney"></param>
        public void ConfirmReturnGoods(ReturnGoods model, ref decimal rmoney, ref decimal pmoney, ref decimal mmoney)
        {
            using (db = DbConfig.GetInstance())
            {
                var orderDetail = db.Queryable<OrderDetail>().SingleOrDefault(t => t.Id == model.OrderDetailId);
                if (orderDetail.SendStatus == OrderDetailSendStatus.已退货 || orderDetail.SendStatus == OrderDetailSendStatus.已换货)
                {
                    throw new Exception("该商品" + orderDetail.SendStatus.ToString());
                }

                if (model.ReturnAmount <= 0)
                {
                    throw new Exception("退款金额必须大于0");
                }

                var order = db.Queryable<Order>().SingleOrDefault(t => t.Id == orderDetail.OrderId);
                if (order.OrderType == OrderType.正常订单 || order.OrderType == OrderType.抢购订单||order.OrderType==OrderType.团购订单)
                {
                    if (model.ReturnAmount > (orderDetail.DiscountPrice * orderDetail.ProductCount))
                    {
                        throw new Exception("退款金额不能大于商品的购买价格");
                    }

                    decimal retunTotal = db.Queryable<ReturnGoods>().Where(t => t.OrderId == model.OrderId && ((int)t.Satus == (int)ReturnStatus.全部退款|| (int)t.Satus == (int)ReturnStatus.部分退款)).ToList().Sum(t => t.ReturnAmount);
                    if (retunTotal + model.ReturnAmount > order.ProductPrice - order.ActivityCouponMoney - order.Discount)
                    {
                        throw new Exception("订单退款金额不足");
                    }

                    if (order.OrderType == OrderType.团购订单)
                    {
                        var act = db.Queryable<GroupMember>().SingleOrDefault(t => t.OrderNo == order.OrderNo);
                        if (act != null)
                        {
                            if (model.ReturnAmount > orderDetail.DiscountPrice * orderDetail.ProductCount - act.RebatePrice)
                            {
                                throw new Exception("退款金额不能大于商品的购买价格");
                            }
                            if (retunTotal + model.ReturnAmount > order.ProductPrice - order.ActivityCouponMoney - order.Discount- act.RebatePrice)
                            {
                                throw new Exception("订单退款金额不足");
                            }

                        }
                    }

                    decimal pointMoney = order.PointsPayMoney;
                    decimal memberMoney = order.MemberMoney;

                    rmoney = model.ReturnAmount;
                    if (retunTotal > 0 && pointMoney > 0)
                    {
                        if (retunTotal > pointMoney)
                        {
                            retunTotal = retunTotal - pointMoney;
                        }
                        else
                        {
                            pointMoney = pointMoney - retunTotal;
                        }
                    }

                    if (retunTotal > 0 && memberMoney > 0)
                    {
                        if (retunTotal > memberMoney)
                        {
                            retunTotal = retunTotal - memberMoney;
                        }
                        else
                        {
                            memberMoney = memberMoney - retunTotal;
                        }
                    }

                    if (pointMoney > 0)
                    {
                        if (rmoney > pointMoney)
                        {
                            rmoney = rmoney - pointMoney;
                            pmoney = pointMoney;
                        }
                        else
                        {
                            pmoney = rmoney;
                            rmoney = 0;

                        }
                    }

                    if (rmoney > 0 && memberMoney > 0)
                    {
                        if (rmoney > memberMoney)
                        {
                            rmoney = rmoney - memberMoney;
                            mmoney = memberMoney;
                        }
                        else
                        {
                            mmoney = rmoney;
                            rmoney = 0;

                        }
                    }

                    if (rmoney == 0)
                    {
                        try
                        {
                            db.IsNoLock = true;//启用无锁查询
                            db.CommandTimeOut = 30000;//设置超时时间
                            db.BeginTran();//开启事务

                            var member = db.Queryable<Member>().SingleOrDefault(t => t.Id == model.MemberId);
                            MemberBalanceDetail mbd = new MemberBalanceDetail();
                            mbd.Point = 0;
                            mbd.Amount = 0;
                            if (pmoney > 0)
                            {
                                member.Points = member.Points + int.Parse((pmoney * 100).ToString("0"));
                                mbd.Point = int.Parse((pmoney * 100).ToString("0"));
                            }

                            if (mmoney > 0)
                            {
                                member.Balance = member.Balance + mmoney;
                                mbd.Amount = mmoney;
                            }

                            if (mbd.Point > 0 || mbd.Amount > 0)
                            {
                                mbd.MemberId = member.Id;
                                mbd.MemberAmount = member.Balance;
                                mbd.MemberPoint = member.Points;
                                mbd.OrderId = model.OrderId;
                                mbd.OrderNo = model.OrderNo;
                                mbd.Note = "订单退款返还";
                                mbd.AddUserId = model.UserId.Value;
                                db.Insert(mbd);
                                db.Update(member);
                            }

                            db.Update<ReturnGoods>(model);
                            orderDetail.SendStatus = OrderDetailSendStatus.已退货;
                            db.Update<OrderDetail>(orderDetail);

                            if (orderDetail.Points > 0)
                            {
                                MemberBalanceDetail mbd1 = new MemberBalanceDetail();
                                member.Points = member.Points - orderDetail.Points;
                                mbd1.MemberId = member.Id;
                                mbd1.Point = orderDetail.Points * -1;
                                mbd1.MemberAmount = member.Balance;
                                mbd1.MemberPoint = member.Points;
                                mbd1.Amount = 0;
                                mbd1.OrderId = model.OrderId;
                                mbd1.OrderNo = model.OrderNo;
                                mbd1.Note = "订单退款扣除积分";
                                db.Insert(mbd1);
                                db.Update(member);
                            }


                            db.CommitTran();
                        }
                        catch
                        {
                            db.RollbackTran();
                            throw;
                        }
                    }

                }
                else
                {
                    throw new Exception("该订单不能退款");
                }
            }
        }


        public int DaiReturnGoodsCount()
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<ReturnGoods>().Where(t => (int)t.Satus ==(int)ReturnStatus.待处理).Count();
            }
        }

        public int DoingReturnGoodsCount()
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<ReturnGoods>().Where(t => (int)t.Satus == (int)ReturnStatus.客服处理中).Count();
            }
        }

        #endregion

        /// <summary>
        /// 统计今日累计销售金额
        /// </summary>
        /// <returns></returns>
        public decimal GetSaleMoney()
        {
            using (db = DbConfig.GetInstance())
            {
                var t1 = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                var t2 = Convert.ToDateTime(DateTime.Now.AddDays(1).ToShortDateString());
                decimal money = 0;
                var list = db.Queryable<Model.Order>()
                   .Where(m => (int)m.PayState ==(int)OrderPayStatus.已支付 && m.PayTime > t1 && m.PayTime < t2)
                   .ToList();
                if (list != null && list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        money += item.ProductPrice;
                    }
                }
                return money;
            }
        }
        /// <summary>
        /// 统计待发货的订单
        /// </summary>
        /// <returns></returns>
        public int GetShipmentPending()
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Model.Order>()
                   .Where(m => m.PayState == OrderPayStatus.已支付 && m.OrderState == OrderStatus.已确认 && m.SendStatus == OrderSendStatus.未发货)
                   .ToList();
                return list.Count;
            }
        }


        public int Getdaipingjia()
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<Model.Order>()
                   .Where(m => m.OrderState == OrderStatus.已收货)
                   .Count();
            }
        }

        public int Getyipingjia()
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<Model.Order>()
                   .Where(m => m.OrderState == OrderStatus.已完成)
                   .Count();
            }
        }

        public int GoodsReceipt(int Id, int memberid)
        {
            int success = 1;
            try
            {
                using (db = DbConfig.GetInstance())
                {
                    var model = db.Queryable<Model.OrderDetail>().SingleOrDefault(t => t.Id == Id);
                    if (model.SendStatus == OrderDetailSendStatus.已发货)
                    {
                        model.SendStatus = OrderDetailSendStatus.确认收货;
                        db.Update<Model.OrderDetail>(model);
                     
                        var list = db.Queryable<Model.OrderDetail>().Where(t => t.OrderNo == model.OrderNo).ToList();
                        var isall = true;
                        foreach (var o in list)
                        {
                            if (o.SendStatus == OrderDetailSendStatus.已发货 || o.SendStatus == OrderDetailSendStatus.未发货)
                            {
                                isall = false;
                            }
                        }
                        var ordermodel = db.Queryable<Model.Order>().SingleOrDefault(t => t.Id == model.OrderId);
                        if (isall)
                        {
                            ordermodel.OrderState = OrderStatus.已收货;
                            db.Update<Model.Order>(ordermodel);
                        }
                        OrderRecord or = new OrderRecord();
                        or.AddTime = DateTime.Now;
                        or.ClientName = "微信";
                        or.OperationUserType = 0;
                        or.OperationId = memberid;
                        or.OrderNo = model.OrderNo;
                        or.OperationNote = "确认收货";
                        or.OrderId = model.OrderId;
                        or.OrderStatus = ordermodel.OrderState;
                        or.PayStatus = ordermodel.PayState;
                        or.Remark = model.ProductName + "被确认收货";
                        or.SendStatus = ordermodel.SendStatus;
                        db.Insert<OrderRecord>(or);
                    }
                }
            }
            catch (Exception e)
            {
                success = 0;
            }
            return success;
        }
    }
}
